<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\analysis\material;

use app\command\BaseWork;
use app\enum\CdcEnum;
use app\service\analysis\material\PicMaterialService;
use app\service\analysis\material\VideoMaterialService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

class MaterialSyncWork extends BaseWork
{
    /**
     * @var int 最大页
     */
    private const MAX_PAGE = 50;

    /**
     * @var int 最大分页
     */
    private const MAX_PAGE_LIMIT = 200;

    protected function configure()
    {
        // 指令配置
        $this->setName('analysis_material_sync_work');
        // 设置参数
        $this->setDescription('系统素材信息同步')
            ->addArgument('type', Argument::REQUIRED, '类型 2：视频  3：图片')
            ->setHelp('php think analysis_material_sync_work [type]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $type = intval($input->getArgument('type'));
        if ($type == CdcEnum::TASK_TYPE_VIDEO) {
            $obj = new VideoMaterialService();
        } elseif ($type == CdcEnum::TASK_TYPE_PICTURE) {
            $obj = new PicMaterialService();
        } else {
            $this->getOutputMessage('获取任务类型失败');
            exit;
        }
        // 超过5min就停止
        $t = time();
        $runTime = 5 * 60;

        while (time() - $t <= $runTime) {
            try {
                $page = 1;
                while ($page <= self::MAX_PAGE) {
                    $items = $obj->getList($page++, self::MAX_PAGE_LIMIT);
                    if (count($items) == 0) {
                        sleep(rand(5, 15));
                        break;
                    }
                    foreach ($items as $model) {
                        $this->getOutputMessage('素材[' . $model->getKey() . ']信息同步开始');
                        if (! $obj->startSync($model)) {
                            $this->getOutputMessage('素材[' . $model->getKey() . ']信息同步失败:' . $obj::getError(0));
                        } else {
                            $this->getOutputMessage('素材[' . $model->getKey() . ']信息同步成功');
                        }
                    }
                }
            } catch (\Exception $e) {
                $this->getOutputMessage('错误：' . $e->getMessage());
                echo $e->getLine() . PHP_EOL;
                echo $e->getFile() . PHP_EOL;
                echo $e->getTraceAsString() . PHP_EOL;
            }
        }
        $this->getOutputMessage('素材同步结束');
    }
}
